package cn.cjx.org.service.impl;

import cn.cjx.basic.exception.BusinessException;
import cn.cjx.basic.utils.BaiduAuditUtils;
import cn.cjx.basic.utils.QueryResult;
import cn.cjx.basic.vo.ShopVo;
import cn.cjx.org.domain.Employee;
import cn.cjx.org.domain.Shop;

import cn.cjx.org.domain.ShopAuditLog;
import cn.cjx.org.mapper.EmployeeMapper;

import cn.cjx.org.mapper.ShopAuditLogMapper;
import cn.cjx.org.mapper.ShopMapper;
import cn.cjx.org.query.ShopQuery;
import cn.cjx.org.service.IEmployeeService;
import cn.cjx.org.service.IShopService;
import cn.cjx.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laoyang
 * @since 2022-03-28
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    /**
     * 店铺入住
     * //一：校验
     *         //1.参数不能为空
     *         //2.店铺是否已经被注册
     *
     *         // 非法校验 用智能审核 @TODO 明天整
     *
     *         //二：管理员是否被注册
     *         // 1.管理员曾今已经注册，并且已经绑定过店铺
     *         // 2.管理员曾今已经注册，没有绑定过店铺
     *
     *
     *         //三：保存数据
     *         //1.保存员工
     *         //2.保存店铺（设置店铺管理员并保存店铺）
     *         //3.修改员工shopId
     * @param shop 基本信息 + 店普管理员信息
     */
    @Override
    public void settlement(Shop shop) {
        //一：校验
        //1.参数不能为空
        String name = shop.getName();
        if (StringUtils.isEmpty(name)) {
            throw new BusinessException("店铺名字不能为空！！！");//抛出自定义业务异常
        }

        // 非法校验 用智能审核
        if (!BaiduAuditUtils.TextCensor(name)) {
            throw new BusinessException("请输入正确的信息，别搞事！");//抛出自定义业务异常
        }

        //2.店铺是否已经被注册
        Shop shopTmp = shopMapper.loadByName(name);
        if (shopTmp != null) {
            throw new BusinessException("店铺已被注册！");//抛出自定义业务异常
        }

        //管理员是否被注册
        Employee admin = shop.getAdmin();
        Employee empTmp = employeeMapper.loadByUserName(admin.getUsername());
        // 1.管理员曾今已经注册，并且已经绑定过店铺
        if (empTmp != null && empTmp.getShopId() != null) {
            throw new BusinessException("该管理员已经拥有店铺，请换其他管理员！！");
        }

        //三：保存员工和店铺
        if(empTmp != null){
            //1.曾今已经存在了empTmp
            shop.setAdmin_id(empTmp.getId());
            shopMapper.save(shop);//返回自增Id
            //3.修改员工shopId
            empTmp.setShopId(shop.getId());
            employeeMapper.update(empTmp);
        }else{
            //2.曾今不存在
            employeeMapper.save(admin);//返回自增Id
            shop.setAdmin_id(admin.getId());
            shopMapper.save(shop);//返回自增Id
            //3.修改员工shopId
            admin.setShopId(shop.getId());
            employeeMapper.update(admin);
        }

        // 2.管理员曾今已经注册，没有绑定过店铺
       /* if(empTmp == null){//没有员工，就新增
            //1.保存员工
            *//*employeeMapper.save(admin);//返回自增Id
         * 这里不应该直接调用别的业务实体的mapper操作数据
         * 而应该将对应的实体业务交给对应的service实现类去操作
         * *//*
            employeeService.save(admin);
            empTmp = admin;
        }
        //只要执行到这里，不管曾经有没有员工，我们这里都有员工了
        //empTmp 此时的empTmp就是店长
        //2.保存店铺（设置店铺管理员并保存店铺）
        shop.setAdminId(empTmp.getId());
        shopMapper.save(shop);//返回自增Id
        //3.修改员工shopId
        empTmp.setShop_id(shop.getId());
        employeeMapper.update(empTmp);
    }*/
    }

    /*
    * 关联查询
    * */
    @Override
    public QueryResult<Shop> queryShops(ShopQuery query) {
        List<Shop> shops = shopMapper.queryShops(query);
        //shops.forEach(System.out::println);
        // skip(5) 前面5个排除了
        List<Shop> collect = shops.stream().skip(query.getPageSize()* (query.getCurrentPage()-1) ).limit(query.getPageSize()).collect(Collectors.toList());
        Long aLong = Long.valueOf(shops.size());
        return new QueryResult<Shop>(aLong,collect);
    }

    @Override
    public void pass(ShopAuditLog log) {
        //修改店铺状态
        Long shopId = log.getShopId();
        Shop shop = shopMapper.loadById(shopId);
        shop.setState(1);
        shopMapper.update(shop);
        //添加审核日志
        log.setAudit_time(new Date());
        log.setState(1);
        //一下两句代码 以后再改
        Employee employee = new Employee();
        employee.setId(1L);
        log.setAuditManager(employee);
        shopAuditLogMapper.save(log);
        //保存日志
        log.setAuditId(325);
        shopAuditLogMapper.save(log);
        //3.发送激活邮件
        //TODO 更改收件人为动态获取的该店铺管理员邮箱
        /*
        Shop shop = shopMapper.loadById(Long.valueOf(log.getShopId()));
        Employee employee = employeeMapper.loadById(shop.getAdminId());

        Employee employee1 = employeeMapper.loadByShopId(shopId);
        */

        SimpleMailMessage simple = new SimpleMailMessage();
        simple.setFrom("2361286244@qq.com");
        //simple.setTo(employee.getEmail());;
        simple.setTo("2361286244@qq.com");
        simple.setSubject("宠物乐园激活请求");
        // message.setText("亲，你的店铺已经初步审核通过，请手动完成激活并使用。激活链接：http://localhost:8080/shop/audit/"+log.getShopId());
        simple.setText("亲，您的激活连接是：" +
                "<a href='http://localhost:8080/shop/activation?shopId="+log.getShopId()+"'>点击激活</a>");
        javaMailSender.send(simple);
    }

    @Override
    public void reject(ShopAuditLog log) {
        //1.把店铺的状态设置为 -1
        Shop shop = shopMapper.loadById(log.getShopId());
        shop.setState(-1);
        shopMapper.update(shop);
        //保存日志
        log.setAuditId(325);
        shopAuditLogMapper.save(log);
        //3.发送激活邮件
        //TODO 更改收件人为动态获取的该店铺管理员邮箱
        SimpleMailMessage simple = new SimpleMailMessage();
        simple.setFrom("2361286244@qq.com");
        simple.setTo("2361286244@qq.com");
        simple.setSubject("驳回，请修改店铺信息，再次提交审核");
        simple.setText("<h1>审核失败</h1><br>"+
                "<span>失败原因："+log.getNote()+"</span><br>"+
                "<a href='http://127.0.0.1:8081/#/register2?id="+log.getId()+"'>点击修改资料</a>");
        javaMailSender.send(simple);
    }

    @Override
    public List<ShopVo> loadEcharts() {
       return shopMapper.loadEcharts();
    }


}
